package naga.x.platform2.channel.wanba.support;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qq.open.ErrorCode;
import com.qq.open.OpenApiV3;
import com.qq.open.OpensnsException;

import naga.x.platform2.App;
import naga.x.platform2.app.Channel;
import naga.x.platform2.utils.HttpUtils;
import naga.x.platform2.utils.StringUtils;

/**
 * 玩吧
 * @see <a href="http://wiki.open.qq.com/wiki/API%E5%88%97%E8%A1%A8">腾讯开放平台</a>
 * @see <a href="http://qzs.qzone.qq.com/qzone/qzact/act/game/wanba/wiki.html">QQ空间·玩吧</a>
 * @see <a href="https://open.mobile.qq.com/api/h5plus/index#api">腾讯移动WEB开发平台</a>
 * @author yang.li
 *
 */
public class QZoneApi {

	public static final String PF = "wanba_ts";
	public static final String ZONEID_ANDROID = "1", ZONEID_IOS = "2";
	public static final int CODE_SUCC = 0;
	public static String protocol;
	
	private static OpenApiV3 api;
	
	private static final Logger LOG = LoggerFactory.getLogger(QZoneApi.class);
	
	public static void init(QZoneConfig config) {
		api = new OpenApiV3(config.getAppId(), config.getAppKey());
		api.setServerName(config.getHost());
		api.setDebug(Channel.QQ_WANBA.debug);
		protocol = config.getProtocol() != null ? config.getProtocol() : "http";
	}
	
	public static final OpenApiV3 getApi() {
		return api;
	}
	
	public static final JSONObject invoke(String path, HashMap<String, String> params) {
		try {
			params.put("pf", PF);
			String ip = HttpUtils.getRequestAddr();
			params.put("userip", ip);
			params.put("format", "json");
			
			JSONObject error = validate(params);
			if (error != null) {
				LOG.error("[QZONE API INVOKE ERROR]PATH[{}]PARAMS[{}]CODE[{}]MSG[{}]", path, params, error.getIntValue("code"), error.getString("message"));
				return error;
			}
			
			String res = getApi().api(path, params, protocol);
			if (App.getInstance().isDebugMode()) {
				LOG.info("[QZONE API INVOKE]PATH[{}]PARAMS[{}]RES[{}]", path, params, res);
			}
			return JSON.parseObject(res);
		} catch (OpensnsException e) {
			LOG.error("[QZONE API INVOKE ERROR]PATH[{}]PARAMS[{}]CODE[{}]MSG[{}]", path, params, e.getErrorCode(), e.getMessage());
			return newError(e.getErrorCode(), e.getMessage());
		} catch (Exception e) {
			LOG.error("[QZONE API INVOKE ERROR]PATH[" + path + "]PARAMS[" + params + "]", e);
			return newError(ErrorCode.NETWORK_ERROR, e.getMessage());
		}
	}
	
	private static JSONObject validate(Map<String, String> params) {
		if (params != null && !params.isEmpty()) {
			Set<Entry<String, String>> set = params.entrySet();
			for (Entry<String, String> e : set) {
				if (StringUtils.isEmpty(e.getValue())) {
					return newError(ErrorCode.PARAMETER_EMPTY, "参数" + e.getKey() + "不能为空");
				}
			}
		}
		return null;
	}
	
	public static JSONObject newError(int code, String message) {
		// {"ret":1,"code":1,"message":"hint"}
		JSONObject error = new JSONObject(4);
		error.put("ret", code);
		error.put("code", code);
		if (StringUtils.isNotEmpty(message)) {
			error.put("message", message);
		}
		return error;
	}
	
	public static String wrapOpenIds(String[] openids) {
		if (openids == null) {
			return "";
		}
		StringBuilder builder = new StringBuilder(128);
		for (int i = 0; i < openids.length; i++) {
			if (i != 0) {
				builder.append('_');
			}
			builder.append(openids[i]);
		}
		return builder.toString();
	}
	
}
